﻿using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System
{
  public static class EnumerableStringExtensions
  {
    public static TResult AggregateString<TSource, TResult>(this IEnumerable<TSource> source, Func<StringBuilder, TSource, StringBuilder> accumulate, Func<StringBuilder, TResult> resultSelector)
    {
      return source.Aggregate(new StringBuilder(), accumulate, resultSelector);
    }

    public static string AggregateString<TSource>(this IEnumerable<TSource> source, Func<StringBuilder, TSource, StringBuilder> accumulate)
    {
      return source.Aggregate(new StringBuilder(), accumulate, builder => builder.ToString());
    }

    public static string AggregateString<TSource>(this IEnumerable<TSource> source, string separator, Func<StringBuilder, TSource, StringBuilder> accumulate)
    {
      return source.Aggregate(
        new StringBuilder(),
        (builder, current) => accumulate(builder, current).Append(separator),
        builder => builder.Length == 0 ? string.Empty : builder.ToString(0, builder.Length - separator.Length));
    }
  }
}